from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from web.settings import BASE_DIR
from .. import models
import time,os
import datetime

# Create your views here.
from django.contrib.auth.hashers import make_password, check_password
from django.core.urlresolvers import reverse
# 数据分页
from django.core.paginator import Paginator
from . viewsIndex import uploads

# 订单显示页面
def orderindex(request):
    # 获取所有订单
    data = models.Order.objects.all()

    # 获取搜索条件
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否有搜索条件
    if types:
        # 判断搜索的类型
        if types == 'receiver':
            search = {types+'__contains':keywords}
            data = data.filter(**search)
            
    # 实例化分页类
    paginator = Paginator(data,2)

    # 获取当前页码数
    p = request.GET.get('p',1)

    # 获取当前页的数据
    data = paginator.page(p)

    context = {'data':data}

    return render(request,'myadmin/order/index.html',context)

# 订单详情
def orderinfo(request):
    
    # 获取订单id
    orderid = request.GET['orderid']
    # print(orderid)
    data = models.OrderInfo.objects.filter(orderid=orderid)

    context = {'data':data}

    return render(request,'myadmin/order/info.html',context)

# 修改订单状态
def orderstatus(request):
    oid = request.GET.get('oid')
    newstatus = request.GET.get('name')
    # print(oid,type(oid))
    # 获取订单信息
    data = models.Order.objects.get(id=oid)
    if newstatus == '未支付':
        data.status = 0
        data.save()
        return JsonResponse({'error':0,'msg':'状态修改成功！'})
    elif newstatus == '未发货':
        data.status = 1
        data.save()
        return JsonResponse({'error':0,'msg':'状态修改成功！'})
    elif newstatus == '已发货':
        data.status = 2
        data.save()
        return JsonResponse({'error':0,'msg':'状态修改成功！'})
    elif newstatus == '已收货':
        data.status = 3
        data.buytime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        data.save()
        return JsonResponse({'error':0,'msg':'状态修改成功！'})
    else:
        data.status = 0
        data.save()
        return JsonResponse({'error':1,'msg':'状态输入有误，修改失败！'})


